package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Department;
import cn.wolfcode.qo.DepartmentQuery;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("department")
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;

    @RequestMapping("list")
    @RequiredPermission(name = "部门列表",expression ="department:list")
    public String list(Model model, DepartmentQuery qo){
        PageInfo<Department> pageInfo = departmentService.query(qo);
        model.addAttribute("pageInfo",pageInfo);
        return "/department/list";
    }

    @RequestMapping("input")
    @RequiredPermission(name = "部门编辑",expression ="department:input")
    public String input(Long id,Model model){
        if (id != null){
            Department department = departmentService.get(id);
            model.addAttribute("department",department);
        }
        return "/department/input";
    }

    @RequestMapping("saveOrUpdate")
    @RequiredPermission(name = "部门保存或更新",expression ="department:saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Department department){
        try {
            //int a = 1/0;
            if (department.getId() != null){
                departmentService.update(department);
            }
            else {
                departmentService.insert(department);
            }
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"部门保存失败,请联系管理员");
        }
    }

    @RequestMapping("/delete")
    @RequiredPermission(name = "部门删除",expression ="department:delete")
    @ResponseBody
    public JsonResult delete(Long id){
        try {
            if (id != null){
                departmentService.delete(id);
            }
            return new JsonResult();
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult(false,"部门删除失败,请联系管理员");
        }

    }
}
